<template>
  <div class="page-container">
    <div v-if="showLoading" class="loading-wrapper">
      <van-loading type="spinner">支付中...</van-loading>
    </div>
    <van-nav-bar
      title="确认信息"
      left-text=""
      right-text=""
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="content-box">
      <div class="content-title">商品内容</div>
      <div class="content-richText">
        {{ goodsDetails.store_name }}
      </div>
    </div>
    <!-- 姓名、性别、年龄、近视度数、散光度数、散光方向、视力 -->
    <van-field
      v-model="userInfo.name"
      type="text"
      label="姓名"
      :placeholder="
        userInfoArr.length !== 0 ? '请填写姓名或放大镜选择' : '请填写姓名'
      "
      :right-icon="userInfoArr.length !== 0 ? 'search' : ''"
      style="margin-top: 10px"
      @click-right-icon="showPopup"
    />
    <van-field
      v-model="userInfo.gender"
      type="text"
      label="性别"
      placeholder="请填写性别"
    />
    <van-field
      v-model="userInfo.age"
      type="text"
      label="年龄"
      placeholder="请填写年龄"
    />
    <van-field
      v-model="userInfo.initialDegreeLeft"
      type="text"
      label="近视度数(左)"
      placeholder="请填写近视度数"
    />
    <van-field
      v-model="userInfo.initialDegreeRight"
      type="text"
      label="近视度数(右)"
      placeholder="请填写近视度数"
    />
    <van-field
      v-model="userInfo.astigmatismLeft"
      type="text"
      label="散光度数(左)"
      placeholder="请填写散光度数"
    />
    <van-field
      v-model="userInfo.astigmatismRight"
      type="text"
      label="散光度数(右)"
      placeholder="请填写散光度数"
    />
    <van-field
      v-model="userInfo.astigmatismDirectionLeft"
      type="text"
      label="散光方向(左)"
      placeholder="请填写散光方向"
    />
    <van-field
      v-model="userInfo.astigmatismDirectionRight"
      type="text"
      label="散光方向(右)"
      placeholder="请填写散光方向"
    />
    <van-field
      v-model="userInfo.visionLeft"
      type="text"
      label="视力(左)"
      placeholder="请填写视力"
    />
    <van-field
      v-model="userInfo.visionRight"
      type="text"
      label="视力(右)"
      placeholder="请填写视力"
    />
    <div
      v-if="reportImgArr.length !== 0"
      style="margin-left: 10px; margin-top: 10px"
    >
      选择验光报告
    </div>
    <div style="margin-top: 10px">
      <div
        v-for="(imgItem, imgIndex) in reportImgArr"
        :key="imgIndex"
        class="van-image"
        style="width: 100px; height: 100px; margin-left: 10px"
      >
        <img
          class="van-image__img"
          :src="imgItem.src"
          @click="showImg(reportImgArr, imgIndex)"
        >
        <i
          :class="`van-icon van-icon-success report_checkbox ${
            imgItem.selected ? 'report_checkbox_selected' : ''
          }`"
          @click="selectImg(imgItem, imgIndex)"
        />
      </div>
    </div>

    <van-field
      v-model="mark"
      type="text"
      label="买家留言"
      placeholder="选填，请先和商家协商一致"
      style="margin-top: 10px"
    />
    <van-submit-bar
      :loading="submitLoading"
      :price="Number(goodsDetails.price) * 100"
      button-text="去付款"
      button-color="#1989fa"
      @submit="onSubmit"
    />

    <!-- 支付弹框 -->
    <van-dialog
      v-model="payDialogVisible"
      title=""
      :show-cancel-button="false"
      :show-confirm-button="false"
      close-on-click-overlay
    >
      <div class="pay-container">
        <van-icon
          name="cross"
          class="pay-dialong-icon-close"
          @click="payDialogVisible = false"
        />
        <div class="pay-dialog-price">￥{{ Number(goodsDetails.price) }}</div>
        <van-radio-group v-model="payRadio">
          <van-cell clickable @click="payRadio = 1">
            <template #title>
              <i class="iconfont icon-adl-weixin" />
              <div>微信支付</div>
            </template>
            <template #right-icon>
              <van-radio :name="1" />
            </template>
          </van-cell>
          <!-- <van-cell clickable @click="payRadio = 2">
            <template #title>
              <i class="iconfont icon-adl-zhifubao" />
              <div>支付宝支付</div>
            </template>
            <template #right-icon>
              <van-radio :name="2" />
            </template>
          </van-cell> -->
        </van-radio-group>
        <div class="pay-dialog-button-box">
          <van-button
            type="info"
            round
            class="pay-dialog-button"
            @click="jumpPayment"
          >去支付</van-button>
        </div>
      </div>
    </van-dialog>
    <!-- 用户信息 -->
    <van-popup v-model="isShowPopup" position="bottom">
      <van-radio-group v-model="userRadio">
        <van-cell-group>
          <van-cell
            v-for="item in userInfoArr"
            :key="item.name"
            :title="item.name"
            clickable
            @click="userRadio = item.name"
          >
            <template #right-icon>
              <van-radio :name="item.name" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
      <van-button
        type="info"
        block
        class="user-popup__button"
        @click="selectdUserInfo"
      >确定</van-button>
    </van-popup>
  </div>
</template>

<script>
import { urlScheme } from '@/api/user'
import { create, orderRecords, pay, detail } from '@/api/order'
import { userInfo } from '@/api/user'
import {
  Button,
  Card,
  Tag,
  Toast,
  GoodsAction,
  Icon,
  RadioGroup,
  Radio,
  SubmitBar,
  Field,
  Dialog,
  Popup,
  ImagePreview
} from 'vant'

let isPayTimer = null

export default {
  name: 'Home',
  components: {
    [Button.name]: Button,
    [Card.name]: Card,
    [Tag.name]: Tag,
    [Toast.name]: Toast,
    [GoodsAction.name]: GoodsAction,
    [Icon.name]: Icon,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [SubmitBar.name]: SubmitBar,
    [Field.name]: Field,
    [Popup.name]: Popup,
    [ImagePreview.Component.name]: ImagePreview.Component
  },
  data() {
    return {
      goodsDetails: JSON.parse(this.$route.query.detailsData), // 商品信息
      userInfo: {}, // 用户信息
      userRadio: null,
      isShowPopup: false,
      userInfoArr: [], // 用户以往记录下拉数据
      reportImgArr: [], // 验光报告
      mark: '', // 订单备注
      payDialogVisible: false, // 支付方式弹窗
      payRadio: 1,
      orderId: null, // 订单id
      showLoading: false, // 支付loading
      submitLoading: false // 提交loading
    }
  },
  created() {
    const status = window.localStorage.getItem('isPaying')
    if (+status === 1) {
      this.showLoading = true
      clearTimeout(isPayTimer)
      this.loopPayStatus(4)
    }
    this.getReportImgArr()
    this.getOrderRecords()
  },
  methods: {
    // 获取用户上传的验光报告
    getReportImgArr() {
      userInfo().then((res) => {
        if (res.error.code === 0) {
          const imgTemp = res.data.report_image
          const reportImgArr = []
          imgTemp.forEach((element) => {
            reportImgArr.push({
              src: element,
              selected: false
            })
          })
          this.reportImgArr = reportImgArr
        }
      })
    },
    // 用户以往记录
    getOrderRecords() {
      orderRecords().then((res) => {
        if (res.error.code === 0) {
          this.userInfoArr = res.data
        }
      })
    },
    // 展现用户信息
    showPopup() {
      this.isShowPopup = true
    },
    // 确定选择
    selectdUserInfo() {
      if (!this.userRadio) {
        Toast('请选择一条数据')
        return
      }
      const temp = this.userInfoArr.find((item) => item.name === this.userRadio)
      this.userInfo = JSON.parse(JSON.stringify(temp))
      this.isShowPopup = false
    },
    // 去付款
    onSubmit() {
      if (!this.userInfo.name) {
        Toast('请输入姓名')
        return
      }
      if (!this.userInfo.gender) {
        Toast('请输入性别')
        return
      }
      if (!this.userInfo.age) {
        Toast('请输入年龄')
        return
      }
      this.submitLoading = true
      const data = {
        product_id: this.goodsDetails.id,
        mark: this.mark
      }
      const selectedArr = []
      this.reportImgArr.forEach((item) => {
        if (item.selected) {
          selectedArr.push(item.src)
        }
      })
      this.userInfo.reportImg = selectedArr
      data.user_message = JSON.stringify(this.userInfo)
      create(data).then((res) => {
        if (res.error.code === 0) {
          this.submitLoading = false
          this.orderId = res.data
          window.localStorage.setItem('orderId', res.data)
          this.payDialogVisible = true
          // Toast('下单成功')
          // this.$router.push({ name: 'home' })
        }
      })
    },
    // 跳转逻辑
    jumpPayment() {
      // if (this.payRadio === 1) {
      //   urlScheme({
      //     order_id: this.orderId
      //   }).then((res) => {
      //     //
      //   })
      //   Toast('功能开发中')
      //   return
      // }
      this.payDialogVisible = false
      this.showLoading = true
      if (this.payRadio === 1) {
        urlScheme({
          order_id: this.orderId
        }).then((res) => {
          window.localStorage.setItem('orderId', this.orderId)
          window.localStorage.setItem('isPaying', '1')
          clearTimeout(isPayTimer)
          this.loopPayStatus(5)
          location.href = res.data
        })
      } else if (this.payRadio === 2) {
        const params = {
          order_id: this.orderId,
          pay_channel: this.payRadio
        }
        pay(params).then((res) => {
          if (res.error.code === 0) {
            window.localStorage.setItem('isPaying', '1')
            clearTimeout(isPayTimer)
            this.loopPayStatus(2)
            // ios里好像不支持window.open打开，所以就改成了a标签模拟点击跳转
            const link = document.createElement('a')
            link.setAttribute(
              'href',
              window.location.origin +
                '/middle.html?jump=' +
                encodeURIComponent(res.data.expend.pay_info)
            )
            document.body.appendChild(link)
            link.click()
          }
        })
      }
    },
    async loopPayStatus(times) {
      if (times === 0) {
        this.showLoading = false
        window.localStorage.removeItem('isPaying')
        window.localStorage.removeItem('orderId')
        Dialog.confirm({
          title: '',
          message:
            '支付异常！订单已生成，请到订单页检查支付是否成功，成功可以预约，失败则需重新支付！',
          showCancelButton: false
        }).then(() => {
          window.history.go(-1)
        })
        return Promise.reject()
      }
      try {
        const order_id = window.localStorage.getItem('orderId')
        const res = await detail({
          order_id: order_id
        })
        const {
          order: { paid }
        } = res.data
        const { code } = res.error
        if (code !== 0) {
          window.history.go(-1)
          window.localStorage.removeItem('isPaying')
          window.localStorage.removeItem('orderId')
        }
        if (paid === 0) {
          const self = this
          isPayTimer = setTimeout(() => {
            self.loopPayStatus(times - 1)
          }, 5000)
        } else if (paid === 1) {
          this.showLoading = false
          Dialog.confirm({
            title: '',
            message: '支付成功，请到订单页预约！',
            showCancelButton: false
          }).then(() => {
            window.history.go(-1)
            window.localStorage.removeItem('isPaying')
            window.localStorage.removeItem('orderId')
          })
        } else {
          Dialog.confirm({
            title: '',
            message: '未能获取支付状态，请刷新页面',
            showCancelButton: false
          }).then(() => {
            window.history.go(-1)
            window.localStorage.removeItem('isPaying')
            window.localStorage.removeItem('orderId')
          })
        }
      } catch (err) {
        console.log(err)
        // window.location.reload()
        // window.localStorage.removeItem('isPaying')
        // window.localStorage.removeItem('orderId')
        const self = this
        isPayTimer = setTimeout(() => {
          self.loopPayStatus(times - 1)
        }, 5000)
      }
    },
    // 选择图片
    selectImg(imgItem, imgIndex) {
      this.reportImgArr[imgIndex].selected = !imgItem.selected
    },
    // 展示图片
    showImg(arr, index) {
      ImagePreview({
        images: arr.map((item) => item.src),
        closeable: true,
        startPosition: index
      })
    },
    // 返回
    onClickLeft() {
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="less" scoped>
.loading-wrapper {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;

  display: flex;
  flex-flow: column nowrap;
  align-items: center;
  justify-content: center;
}
.page-container {
  height: 100vh;
  padding-bottom: 60px;
  box-sizing: border-box;
  overflow: auto;
}
.van-submit-bar__bar {
  width: 100%;
  max-width: 540px;
  margin: 0 auto;
  justify-content: flex-end;
  .van-button {
    width: 180px;
    height: 33px;
    margin-right: 20px;
  }
}
.content-box {
  background-color: #ffffff;
  margin-top: 10px;
}
.header-box {
  padding: 10px;
}
.content-title {
  border-bottom: 1px solid #f5f5f5;
  padding: 10px;
  font-size: 14px;
  color: #868686;
}
.content-richText {
  padding: 10px;
  font-size: 14px;
}

.pay-dialong-icon-close {
  position: absolute;
  right: 12px;
  top: 12px;
  &:hover {
    cursor: pointer;
  }
}
.pay-dialog-price {
  line-height: 80px;
  text-align: center;
  font-weight: bold;
  font-size: x-large;
  color: #e56015;
}
.pay-dialog-button-box {
  text-align: center;
  padding: 10px;
}
.pay-dialog-button {
  height: 35px;
  width: 100%;
}
.pay-container .van-cell__title {
  display: flex;
  > div {
    margin-left: 5px;
  }
}
.report_checkbox {
  position: absolute;
  top: 0;
  right: 0;
  color: #fff;
  border: 1px solid #c8c9cc;
  color: transparent;
}
.report_checkbox_selected {
  color: #fff;
  background-color: #1989fa;
  border-color: #1989fa;
}
</style>
